include(CheckIncludeFiles)
include(CheckSymbolExists)

check_include_files(syslog.h HAVE_SYSLOG_H)
check_include_files(openssl/ssl.h HAVE_OPENSSL_H)
check_include_files(pthread.h HAVE_PTHREAD_H)

check_symbol_exists(LOG_EMERG   "syslog.h" HAVE_LOG_EMERG_S)
check_symbol_exists(LOG_ALERT   "syslog.h" HAVE_LOG_ALERT_S)
check_symbol_exists(LOG_CRIT    "syslog.h" HAVE_LOG_CRIT_S)
check_symbol_exists(LOG_ERR     "syslog.h" HAVE_LOG_ERR_S)
check_symbol_exists(LOG_WARNING "syslog.h" HAVE_LOG_WARNING_S)
check_symbol_exists(LOG_NOTICE  "syslog.h" HAVE_LOG_NOTICE_S)
check_symbol_exists(LOG_INFO    "syslog.h" HAVE_LOG_INFO_S)
check_symbol_exists(LOG_DEBUG   "syslog.h" HAVE_LOG_DEBUG_S)

macro(BY_INTERNAL_TEST_RUN BY_TEST)
	if("${BY_TEST}_COMPILE" MATCHES "^${BY_TEST}_COMPILE$")
		set(MACRO_CHECK_FUNCTION_DEFINITIONS "-D${BY_TEST} ${CMAKE_REQUIRED_FLAGS}")

		if(CMAKE_REQUIRED_LIBRARIES)
			set(BY_TEST_ADD_LIBRARIES "-DLINK_LIBRARIES:STRING=${CMAKE_REQUIRED_LIBRARIES}")
		endif(CMAKE_REQUIRED_LIBRARIES)
		
		message(STATUS "Performing Backtory Test ${BY_TEST}")
		try_run(
			${BY_TEST}
			${BY_TEST}_COMPILE
			${CMAKE_BINARY_DIR}
			${backtory_SOURCE_DIR}/CMake/BacktoryTests.c
			CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS}
			"${BY_TEST_ADD_LIBRARIES}"
			OUTPUT_VARIABLE OUTPUT
		)
		
		if(${BY_TEST}_COMPILE AND NOT ${BY_TEST})
			set(${BY_TEST} 1 CACHE INTERNAL "Backtory test ${FUNCTION}")
			message(STATUS "Performing Backtory Test ${BY_TEST} - Success")
		else(${BY_TEST}_COMPILE AND NOT ${BY_TEST})
			message(STATUS "Performing Backtory Test ${BY_TEST} - Failed")
			set(${BY_TEST} "" CACHE INTERNAL "Backtory test ${FUNCTION}")
			file(
				APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log"
				"Performing Backtory Test ${BY_TEST} failed with the following output:\n"
				"${OUTPUT}"
			)
			if(${BY_TEST}_COMPILE)
				file(
					APPEND
					"${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log"
					"There was a problem running this test\n"
				)
			endif(${BY_TEST}_COMPILE)
			file(APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log" "\n\n")
		endif(${BY_TEST}_COMPILE AND NOT ${BY_TEST})
	endif("${BY_TEST}_COMPILE" MATCHES "^${BY_TEST}_COMPILE$")
endmacro(BY_INTERNAL_TEST_RUN)

foreach(BY_TEST
	HAVE_GLIBC_STRERROR_R
	HAVE_POSIX_STRERROR_R
	)
	by_internal_test_run(${BY_TEST})
endforeach(BY_TEST)

configure_file(config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)

add_subdirectory(backtory)